/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Services;

import java.io.Serializable;
import javax.persistence.*;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import Entity.Veterinarian;
import Entity.Appointment;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
/**
 *
 * @author microraptor
 */
public class VeterinarianService implements Serializable{
    private EntityManagerFactory emf = null;
    AppointmentService appoinmentService = new AppointmentService(emf);
    
    public VeterinarianService (EntityManagerFactory emf){
        this.emf = emf;
    }
    
    public EntityManager getEntityManager(){
        return emf.createEntityManager();
    }
    
    public Veterinarian findPet(Long id){
        EntityManager em = null;
        Veterinarian veterinarian = null;
        try{
            em = getEntityManager();
            veterinarian = em.find(Veterinarian.class, id);
        }finally{
            if(em != null){
                em.close();
            }
        }
        return veterinarian;
    }
    
    public void crear(Veterinarian veterinarian){
        EntityManager em = null;
        try{
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(veterinarian);
            em.getTransaction().commit();
        }finally{
            if(em != null){
                em.close();
            }
        }
    }
    
    public void edit(Veterinarian veterinarian) throws Exception{
        EntityManager em = null;
        try{
            em = getEntityManager();
            em.getTransaction().begin();
            veterinarian = em.merge(veterinarian);
            em.getTransaction().commit();
        }catch (Exception ex){
            String msg = ex.getLocalizedMessage();
            if (msg == null ||  msg.length() == 0){
                Long id = veterinarian.getId();
                if (findPet(id) == null){
                    throw new Exception("The pet with id "+id+" no longer exists.");
                }
            }
            throw ex;
        }finally{
            if (em != null){
                em.close();
            }
        }
    }
    
    public void destroy (Long id) throws Exception{
        EntityManager em = null;
        try{
            em=getEntityManager();
            em.getTransaction().begin();
            Veterinarian veterinarian;
            try{
                veterinarian = em.getReference(Veterinarian.class, id);
                veterinarian.getId();
            }catch(EntityNotFoundException ex){
                throw new Exception ("The pet with id "+id+" no longer exists.", ex);
            }
            em.remove(veterinarian);
            em.getTransaction().commit();
        }finally{
            if(em != null){
                em.close();
            }
        }
    }
    
    public List<Veterinarian> findVeterinarianEntities(){
        return findVeterinarianEntities(true, -1,-1);
    }
    
    public List<Veterinarian> findVeterinarianEntities(int maxResults, int firstResult){
        return findVeterinarianEntities(false, maxResults, firstResult);
    }
    
    private List<Veterinarian> findVeterinarianEntities(boolean all, int maxResults, int firstResult)    {
        EntityManager em = getEntityManager();
        try{
            CriteriaQuery cq =  em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Veterinarian.class));
            Query q = em.createQuery(cq);
            if(!all){
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            
            for (int i =0;i<q.getResultList().size(); i++){
                Veterinarian veterinarian = (Veterinarian) q.getResultList().get(i);
                long veterinarianId = veterinarian.getId();
                Query query = em.createNativeQuery("select ID from appointment"
                        + " where VETERINARIAN_PersonID = " + veterinarianId);
                veterinarian.setAppointments(findAppointments(query));
            }   
            return q.getResultList();
        }finally{
            em.close();
        }
    }
    
    @SuppressWarnings ("empty-statement")
    public Veterinarian findVeterinarian(Long id){
        EntityManager em = getEntityManager();
        try{
            Veterinarian vet = em.find(Veterinarian.class, id);
            long vetId = vet.getId();
            Query query = em.createNativeQuery("select ID from appointment"
                        + " where VETERINARIAN_PersonID = " + vetId);
            vet.setAppointments(findAppointments(query));
            return vet;
        }finally{
            em.close();
        }
    }
    
    private List<Appointment> findAppointments(Query query){
        List<Appointment> appoinments = new ArrayList<>();
        for(int i=0; i<query.getResultList().size(); i++){
            Long appoId = (Long) query.getResultList().get(i);
            appoinments.add(appoinmentService.findAppointment(appoId));
        }
        return appoinments;
    }
    
    public int getAppointmentCount(){
        EntityManager em = getEntityManager();
        try{
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Veterinarian> rt = cq.from(Veterinarian.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long)q.getSingleResult()).intValue();
        }finally{
            em.close();
        }
    }
}
